package at.jku.mc.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

// Beim verwenden von SimpleCursorAdapter, werden die Datenmodelle sinnlos. Code entfernen!
// Anm.: Klassen bis auf TodoList und Task im Datenmodell sind nun @deprecated.

public final class TodoListProvider {
	private static final int TODOLIST_ARCHIVED = 1;

	// Database fields
	private SQLiteDatabase database;
	private DatabaseHelper dbHelper;

	public TodoListProvider(Context context) {
		dbHelper = new DatabaseHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
		if (!database.isReadOnly()) {
			// Enable foreign key constraints
			database.execSQL("PRAGMA foreign_keys=ON;");
		}
	}

	public void close() {
		dbHelper.close();
	}

	public void createTodoList(String title, String description, long category) {
		ContentValues values = new ContentValues();
		values.put(DatabaseHelper.TODOLIST_COLUMN_TITLE, title);
		values.put(DatabaseHelper.TODOLIST_COLUMN_DESCRIPTION, description);
		values.put(DatabaseHelper.TODOLIST_COLUMN_CATEGORY, category);
		values.put(DatabaseHelper.TODOLIST_COLUMN_ISARCHIVED, false);
		long insertId = database.insert(DatabaseHelper.TABLE_TODOLIST, null,
				values);
		Cursor cursor = database.query(DatabaseHelper.TABLE_TODOLIST,
				null, DatabaseHelper.TODOLIST_COLUMN_ID + " = "
						+ insertId, null, null, null, null);
		cursor.moveToFirst();
		cursor.close();
	}

	public void deleteTodoList(long id) {
		System.out.println("List deleted with id: " + id);
		database.delete(DatabaseHelper.TABLE_TODOLIST,
				DatabaseHelper.TODOLIST_COLUMN_ID + " = " + id, null);
	}

	public int archiveList(long id) {
		System.out.println("List archived with id: " + id);
		ContentValues args = new ContentValues();
		args.put(DatabaseHelper.TODOLIST_COLUMN_ISARCHIVED, TODOLIST_ARCHIVED);
		return database.update(DatabaseHelper.TABLE_TODOLIST, args,
				DatabaseHelper.TODOLIST_COLUMN_ID + " = " + id, null);
	}

	public Cursor getNotArchivedTodoLists() {
		// DESC -> hoechste id zuerst anzeigen
		// TODO: nicht hoechste id, sondern Reihenfolge festlegbar
		Cursor cursor = database.query(DatabaseHelper.TABLE_TODOLIST,
				null, DatabaseHelper.TODOLIST_COLUMN_ISARCHIVED + " = "
						+ 0, null, null, null,
				DatabaseHelper.TODOLIST_COLUMN_ID + " DESC");
		return cursor;
	}

	public Cursor getArchivedTodoLists() {
		// DESC -> hoechste id zuerst anzeigen
		// TODO: nicht hoechste id, sondern Reihenfolge festlegbar
		Cursor cursor = database.query(DatabaseHelper.TABLE_TODOLIST,
				null, DatabaseHelper.TODOLIST_COLUMN_ISARCHIVED + " = "
						+ 1, null, null, null,
				DatabaseHelper.TODOLIST_COLUMN_ID + " DESC");
		return cursor;
	}

}
